package com.java.simple.smallspring.context.annotation;

import cn.hutool.core.util.StrUtil;
import com.java.simple.smallspring.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import com.java.simple.smallspring.beans.factory.config.BeanDefinition;
import com.java.simple.smallspring.beans.factory.support.BeanDefinitionRegistry;
import com.java.simple.smallspring.stereotype.Component;
import java.util.Objects;
import java.util.Set;

/**
 * @author zhoujunlin
 * @date 2022年09月27日 17:32
 * @desc
 */
public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateComponentProvider {

    private BeanDefinitionRegistry registry;

    public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
        this.registry = registry;
    }

    public void doScan(String... basePackages) {
        for (String basePackage : basePackages) {
            Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
            for (BeanDefinition beanDefinition : candidates) {
                String scope = resolveBeanScope(beanDefinition);
                if (StrUtil.isNotBlank(scope)) {
                    beanDefinition.setScope(scope);
                }
                registry.registerBeanDefinition(determineBeanName(beanDefinition), beanDefinition);
            }
        }
        // 注册 处理注解(@Autowired @Value)的BeanPostProcessor内部Bean 因此这个类不需要在xml中配置
        registry.registerBeanDefinition("com.java.simple.smallspring.context.annotation.internalAutowiredAnnotationProcessor", new BeanDefinition(AutowiredAnnotationBeanPostProcessor.class));
    }

    /**
     * 解析bean 作用域
     *
     * @param beanDefinition
     * @return
     */
    private String resolveBeanScope(BeanDefinition beanDefinition) {
        Class<?> beanClass = beanDefinition.getBeanClass();
        Scope scope = beanClass.getAnnotation(Scope.class);
        if (Objects.nonNull(scope)) {
            return scope.value();
        }
        return StrUtil.EMPTY;
    }

    /**
     * 获取beanName
     *
     * @param beanDefinition
     * @return
     */
    private String determineBeanName(BeanDefinition beanDefinition) {
        Class<?> beanClass = beanDefinition.getBeanClass();
        Component component = beanClass.getAnnotation(Component.class);
        String value = component.value();
        if (StrUtil.isBlank(value)) {
            value = StrUtil.lowerFirst(beanClass.getSimpleName());
        }
        return value;
    }


}
